// store/modules/permission.js
import { constantRoutes } from '@/router'
import { getMenuListApi } from '@/api/menu'
import { getUserId, getUserType } from '@/utils/auth'
import Layout from '@/layout'

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function loadView(view) {
  return (resolve) => require([`@/views${view}`], resolve)
}

function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    if (!route.path) return // 过滤掉没有 path 的路由

    const temp = { ...route }
    if (hasPermission(roles, temp)) {
      if (temp.component) {
        if (temp.component === 'Layout') {
          temp.component = Layout
        } else {
          try {
            temp.component = loadView(temp.component)
          } catch (error) {
            console.error(`Component load error: ${temp.component}`, error)
          }
        }
      }

      if (temp.children) {
        temp.children = filterAsyncRoutes(temp.children, roles)
      }
      res.push(temp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = [...constantRoutes, ...routes]
  }
}

const actions = {
  async generateRoutes({ commit }, roles) {
    try {
      const res = await getMenuListApi({
        userId: getUserId(),
        userType: getUserType()
      })

      const accessedRoutes = filterAsyncRoutes(res.data, roles)
      commit('SET_ROUTES', accessedRoutes)
      return accessedRoutes
    } catch (error) {
      console.error('Error generating routes:', error)
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
